<!--总保费和出单量趋势图-->
<template>
    <section class="section">
        <div class="chart-box">
            <ul class="chart-box__form">
                <li 
                v-for="(item,index) in list" 
                :key="index"
                @click="handelSelect(item.key)"
                :class="selectedItem===item.key? 'chart-box__form--active':''"
                >
                {{item.key}}
            </li>
            </ul>
            <div class="chart" ref="chartDom"></div>
        </div>
    </section>
</template>

<script setup>
import { ref, onMounted,computed,onBeforeUnmount} from 'vue'
import * as echarts from 'echarts'
import { rem2px } from "../../utils/scale"

// 获取图表DOM
const chartDom = ref(null)
let myChart = null
const chartOption=ref(null)
const selectObj=ref(['总保费和出单量趋势图','服务包销售额和销量的趋势图'])
const selectedItem=ref('总保费和出单量趋势图')

function generateSmoothTrend(length = 12, start = 1000, variance = 0.1) {
  const data = [start];
  for (let i = 1; i < length; i++) {
    const last = data[i - 1];
    // 在 last 的基础上变化（±10%）
    const delta = last * (Math.random() * variance * 2 - variance);
    data.push(Math.round(last + delta));
  }
  return data;
}

//模拟数据
const list = ref([
  {
    key: "总保费和出单量趋势图",
    arr: [
      {
        name: '出单量',
        value: generateSmoothTrend(12, 1000, 0.5),
        lineColor: "#BFDFFF",
        colors: ["#2d79f3", "#0603FF"]
      },
      {
        name: '费用',
        value: generateSmoothTrend(12, 20000, 0.5),
        lineColor: "#FDFFCC",
        colors: ['#C1F51F', '#40ff3b']
      }
    ]
  },
  {
    key: "服务包销售额和销量的趋势图",
    arr: [
      {
        name: '出单量',
        value: generateSmoothTrend(12, 1000, 0.5),
        lineColor: "#BFDFFF",
        colors: ["#2d79f3", "#0603FF"]
      },
      {
        name: '费用',
        value: generateSmoothTrend(12, 20000, 0.5),
        lineColor: "#FDFFCC",
        colors: ['#C1F51F', '#40ff3b']
      }
    ]
  }
])


const month = Array.from({ length: 12 }, (_, i) => `${i + 1}月`);

const handelSelect=(item)=>{
    selectedItem.value=item
    updateLineOption()
}
const lineOption=(title,xData,y1Name,y2Name,series)=>({
  grid: {left: '2%',right: '6%',top:"20%",bottom: '12%',containLabel: true },
  legend: {  
    bottom:"0%",
    textStyle: {
      color: '#fff' , // 图例文字变白
      fontSize:rem2px(.8),
    }
  },
  xAxis: [
    {
      type: 'category',
      axisLabel: {
        color: '#fff',  // X轴刻度值变白
        fontSize:rem2px(.6),
      },
      boundaryGap: false,
      data: xData
    }
  ],
  yAxis: [
    {
      type: 'value',
      name:y1Name,
      nameLocation: 'end',
      splitLine:{show:false},
      axisLabel: {
        color: '#fff',  // X轴刻度值变白
        fontSize:rem2px(.6),
        formatter: function (value) {
          return value.toFixed(0);
        }
      },
      nameTextStyle: {
        color: '#fff',  // 单位 "(条)" 也变白
        fontSize:rem2px(.6),
      }

    },
    {
      type: 'value',
      name:y2Name,
      nameLocation: 'end',
      splitLine:{show:false},
      axisLabel: {
        color: '#fff',  // X轴刻度值变白
        fontSize:rem2px(.6),
      },
      nameTextStyle: {
        color: '#fff',  // 单位 "(条)" 也变白
        fontSize:rem2px(.6),
      }

    }
  ],
 series
})

const updateLineOption = () => {
    const tmpData=list.value.find(x=>x.key===selectedItem.value)?.arr
    const series=tmpData.map((item,index)=>({
        name: item.name,
        type: 'line',
        smooth: true,
        symbol: 'none',
        lineStyle: {
        width: 1,
        color: item.lineColor // 折线颜色更浅
        },
        areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: item.colors[0] },
            { offset: 1, color: item.colors[1] }
        ]),
        opacity: 0.45
        },
        data: item.value,
        yAxisIndex:index,
    }))
    

    chartOption.value = lineOption('', month,'条','元',series);

    if (chartDom.value) {
        myChart = echarts.init(chartDom.value); // 这里必须用window.echarts
        myChart.setOption(chartOption.value); // 注意要.value
    }
};

// 初始化图表
onMounted(() => {
  if (chartDom.value) {
    myChart = echarts.init(chartDom.value);

    updateLineOption()
    
    const observer = new ResizeObserver(() => {
      myChart?.resize();
    });
    observer.observe(chartDom.value);

    onBeforeUnmount(() => {
      observer.disconnect(); // 停止监听
      myChart?.dispose();
    });
  }

});
</script>

<style lang="scss" scoped>
@import "../../assets/style/main.scss";
$color-border:#494949;

.section{
    width: 100%;   
    margin-top:.8rem;
}
.chart-box{
    position: relative;
    border-top: 1px solid $color-border;
    border-bottom: 1px solid $color-border;
    width: 100%;
    height: 16.8rem;
    background-color: rgba(0,0,0,0.2);
    &__form{
        position: absolute;
        width: 100%;
        list-style:none;
        display: flex;
        justify-content: center;
        margin-top: .4rem;
        z-index: 1;
        &--active{
            color: #fff !important;
        }
        li{
            padding:2px 3px;
            font-size:.8rem;
            background: linear-gradient(to right, #778aa5 0%, #3a394e 50%, #778aa5 100%);
            color: #ccc;
            cursor: pointer;
        }
    }
}
.chart{
  width: 100%;
  height: 16.8rem;
  }

</style>